package com.wuyou.sso.common.utils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * BeanUtils
 *
 * @Date 2025/4/27 16:12
 * @Author 无忧
 */
public class BeanUtils {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";


    public static Map<String, String> beanToStringMap(Object bean){
        if (bean == null) return Collections.emptyMap();

        Map<String, String> result = new LinkedHashMap<>();
        Class<?> clazz = bean.getClass();

        // 获取所有字段（包括私有字段）
        for (Field field : getAllFields(clazz)) {
            try {
                field.setAccessible(true);
                Object value = field.get(bean);
                String key = field.getName();
                String strValue = convertToString(value);
                result.put(key, strValue);
            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }
        return result;
    }

    /**
     * 递归获取类及其父类的所有字段
     */
    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

    /**
     * 将对象转换为字符串
     */
    private static String convertToString(Object value) {
        if (value == null) return null;

        // 处理日期类型
        if (value instanceof Date) {
            return new SimpleDateFormat(DATE_FORMAT).format((Date) value);
        }

        // 处理集合类型
        if (value instanceof Collection) {
            return ((Collection<?>) value).stream()
                    .map(BeanUtils::convertToString)
                    .collect(Collectors.joining(", "));
        }

        // 处理数组
        if (value.getClass().isArray()) {
            return Arrays.stream((Object[]) value)
                    .map(BeanUtils::convertToString)
                    .collect(Collectors.joining(", "));
        }

        // 其他类型直接调用 toString()
        return value.toString();
    }
}
